<?php

// Acceso restringido
defined('JL') or die('Acceso restringido');
define('NEWSLETTER_KEY', 'NEWSLETTER_KEY');

/**
 * NewsletterController
 * 
 * @package JL Panel
 * @author JLQ
 * @copyright 2009
 * @version 1.0
 * @access public
 */
class NewsletterController extends JLControllerBase {

    private $config = null;
    private $path = "Newsletter";
    private $title = "Système d'Actualisation CSME > Newsletter";
    private $data = null;

    function Index() {
        require JLPATH_MODELS . DS . "NewsletterModel.php";
        $newsletter = new NewsletterModel();
        $newsletters = $newsletter->getNewsletters();
        $data['newsletters'] = $newsletters;

        $data['classcurrent7'] = ' class="current"';
        $this->View->Show("Affilies", $this->title, $data);
    }

    function Newsletter() {
        require JLPATH_MODELS . DS . "StateModel.php";
        $states = new StateModel();
        $data['states'] = $states->getStates();

        $data['classcurrent7'] = ' class="current"';
        $this->View->Show($this->path, $this->title, $data);
    }

    /**
     * ContactController::deleteContact()
     * 
     * @return
     */
    function deleteContact() {
        $ids = $_POST['_ids'];
        $ides = explode(",", $ids);
        require JLPATH_MODELS . DS . "AffiliesModel.php";
        $affilies = new AffiliesModel();

        $i = 0;
        foreach ($ides as $id) {
            $_true = $affilies->deleteAffilies($id);
            if (!$_true)
                break;

            $i++;
        }
        $nodelete = count($ides) - $i;

        if ($_true)
            echo $i . "  Donnée(s) effacer";
    }

    /**
     * ContactController::deleteContact()
     * 
     * @return
     */
    function insertNewsletter() {
        require JLPATH_MODELS . DS . "NewsletterModel.php";
        $newsletter = new NewsletterModel();
        $var_nom_newsletter = $_POST['_var_nom_newsletter'];
        $int_id_state = $_POST['_int_id_state'];
        $_true = $newsletter->insertNewsletter($var_nom_newsletter, $int_id_state);
        if ($_true != 0)
            echo $_true;
        else
            echo "";
        exit();
    }

    /**
     * ContactController::getNewsletter()
     * 
     * @return
     */
    function getNewsletter() {
        $_id = $_POST['_id'];
        require JLPATH_MODELS . DS . "NewsletterModel.php";
        $newsletter = new NewsletterModel();

        $_true = $newsletter->getNewsletter($_id);
        $var_nom_newsletter = $_true['var_nom_newsletter'];
        $int_id_state = $_true['int_id_state'];

        echo $var_nom_newsletter . "_%_" . $int_id_state;
    }

    function getActualitesBox() {
        $_id = $_GET['_id'];
        require JLPATH_MODELS . DS . "ActualiteBoxModel.php";
        $ActBoxModel = new ActualiteBoxModel();
        $actBox = $ActBoxModel->getActualiteBoxByIdNewsletter($_id);

        require JLPATH_LIBRARIES . DS . "Tools" . DS . "JSON.class.php";
        $json = new Services_JSON();
        $response->item1 = $actBox;
        echo $json->encode($response);
    }

    function updateActualiteBox() {
        $_id = $_POST['_col1'];
        $_id2 = $_POST['_col2'];

        require JLPATH_MODELS . DS . "ActualiteBoxModel.php";
        $ActBoxModel = new ActualiteBoxModel();
        $ids = explode(",", $_id);
        $ids2 = explode(",", $_id2);
        foreach ($ids as $v) {
            $id = explode("-", $v);
            $ActBoxModel->updateActualiteBox($id[0], "col01", $id[1]);
        }
        foreach ($ids2 as $v) {
            $id = explode("-", $v);
            $ActBoxModel->updateActualiteBox($id[0], "col02", $id[1]);
        }
        echo "OK";
    }

    function getActualiteById() {
        require JLPATH_MODELS . DS . "ActualiteBoxModel.php";
        $ActBoxModel = new ActualiteBoxModel();
        $var_column = $_POST['_var_column'];
        $int_id_actualite = $_POST['_int_id_actualite'];
        $int_id_newsletter = $_POST['_int_id_newsletter'];
        $int_no_csme_actualite = $_POST['_int_no_csme_actualite'];
        $_true = $ActBoxModel->insertActualiteBox($var_column, $int_id_actualite, $int_no_csme_actualite, $int_id_newsletter);
        echo $_true;
    }

    function insertOtherActualite() {
        require JLPATH_MODELS . DS . "ActualiteModel.php";
        $OtherActualite = new ActualiteModel();
        $var_title = $_POST['_var_title'];
        $txt_description = $_POST['_txt_description'];
        $_true = $OtherActualite->InsertActualite($var_title, $txt_description, 0, 0, 0, 27, 0, 3);
        if ($_true > 0)
            echo $_true;
        else
            "";
    }

    function updateOtherActualite() {
        require JLPATH_MODELS . DS . "ActualiteModel.php";
        $OtherActualite = new ActualiteModel();
        $_id = $_POST['_id'];
        $var_title = $_POST['_var_title'];
        $txt_description = $_POST['_txt_description'];
        echo $OtherActualite->UpdateActualite($_id, $var_title, $txt_description, 0, 27, 3);
    }

    function getOtherActualite() {
        $_id = $_GET['_id'];
        require JLPATH_MODELS . DS . "ActualiteModel.php";
        $OtherActualite = new ActualiteModel();
        $_true = $OtherActualite->SelectActualite($_id);

        require JLPATH_LIBRARIES . DS . "Tools" . DS . "JSON.class.php";
        $json = new Services_JSON();
        echo $json->encode($_true);
    }

    function deleteOtherActualite() {
        require JLPATH_MODELS . DS . "ActualiteModel.php";
        $OtherActualite = new ActualiteModel();
        $_id = $_POST['_id'];
        $_true = $OtherActualite->DeleteActualite($_id);
        if ($_true)
            echo "Donnée effacer!";
    }

    function deleteActualiteBox() {
        require JLPATH_MODELS . DS . "ActualiteBoxModel.php";
        $ActBoxModel = new ActualiteBoxModel();
        $_id = $_POST['_id'];
        $_true = $ActBoxModel->deleteActualiteBox($_id);
        if ($_true)
            echo "Donnée effacer!";
    }

    /**
     * ContactController::updateNewsletter()
     * 
     * @return
     */
    function updateNewsletter() {
        require JLPATH_MODELS . DS . "NewsletterModel.php";
        $newsletter = new NewsletterModel();
        $id = $_POST['_id'];
        $var_nom_newsletter = $_POST['_var_nom_newsletter'];
        $int_id_state = $_POST['_int_id_state'];
        $_true = $newsletter->updateNewsletter($id, $var_nom_newsletter, $int_id_state);
        if ($_true)
            echo "Données sauvegarder avec succès.";
        else
            echo "";
    }

    /**
     * ContactController::deleteNewsletter()
     * 
     * @return
     */
    function deleteNewsletter() {
        $_ids = $_POST['_ids'];
        require JLPATH_MODELS . DS . "NewsletterModel.php";
        $newsletter = new NewsletterModel();
        require JLPATH_MODELS . DS . "ActualiteBoxModel.php";
        $ActBoxModel = new ActualiteBoxModel();

        $users = explode("-", $_ids);
        $i = 0;
        foreach ($users as $v) {
            if (trim($v) != "") {
                $val = $newsletter->deleteNewsletter(trim($v));
                if (!$val)
                    break;
                else
                    $ActBoxModel->deleteActualiteBoxByIdNewsletter(trim($v));
                $i++;
            }
        }

        $nodelete = (count($users) - $i) - 1;

        if (!$val) {
            echo $i . " donnée(s) effacer! \n$nodelete donnée(s) n'a pu être effacer. Veuillez changer l'état à Provisoire.";
        }
        else
            echo $i . " Donnée(s) effacer!";
    }

    function getAllAffilies() {
        require JLPATH_MODELS . DS . "AffiliesModel.php";
        $affilies = new AffiliesModel();

        $_true = $affilies->getAllAffilies();

        require JLPATH_LIBRARIES . DS . "Tools" . DS . "JSON.class.php";
        $json = new Services_JSON();
        echo $json->encode($_true);
    }

    function sendMail() {
        $FULLNAME = $_POST['_nom'];
        $EMAIL = $_POST['_email'];
        $CODE = $_POST['_code'];
        $SUBJECT = "CSME Newsletter - " . $this->getDataFrance();
        $BODY = $_SESSION[NEWSLETTER_KEY];
        $BODY = str_replace("%FULLNAME%", $FULLNAME, $BODY);
        $BODY = str_replace("%CODE%", $CODE, $BODY);

        require JLPATH_LIBRARIES . DS . "Tools" . DS . "phpmailer" . DS . "phpmailer.php";

        $mail = new PHPMailer();
        $mail->PluginDir = "";
        $mail->IsHTML(TRUE);
        $mail->CharSet = "utf-8";
        $mail->IsMail();
        $mail->Timeout = 12;
        $mail->From = "newsletter@csme.fr";
        $mail->FromName = "Club Sportif Multisections d’Epinay-sur-Seine";
        $mail->Subject = $SUBJECT;
        $mail->Body = $BODY;
        $mail->AddAddress($FULLNAME . " <" . $EMAIL . ">");
        $mail->Send();
        $mail->ClearAddresses();
        echo "OK";
    }

    function getDataFrance($fulldate = TRUE) {
        $_month = array("Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
        $_year = date("Y");

        if ($fulldate) {
            $_days = array("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche");
            $fecha = "le " . $_days[intval(date("N")) - 1] . " " . date("j") . " " . $_month[intval(date("n")) - 1] . " " . $_year;
        } else {
            $fecha = $_month[intval(date("n")) - 1] . " " . $_year;
        }

        return $fecha;
    }

    function getFrenchMonth() {
        $_month = array("Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
        return $_month[intval(date("n")) - 1];
    }

    function getMessageNewsletter($id = NULL, $for_browser = FALSE) {

        $id = filter_var(!empty($id) ? $id : $_GET['_idNewsletter'], FILTER_SANITIZE_NUMBER_INT);

        require JLPATH_MODELS . DS . "NewsletterModel.php";
        require JLPATH_MODELS . DS . "ActualiteModel.php";
        require JLPATH_HELPERS . DS . "NewsletterHelper.class.php";
        require JLPATH_LIBRARIES . DS . 'Smarty' . DS . 'Smarty.class.php';

        $news = new NewsletterModel();
        $smarty = new Smarty();
        $newsletter_helper = new NewsletterHelper();
        $actualites = new ActualiteModel();
        $actualites = $actualites->getGroupActualites();
        $newsletter = $news->getNewsletter($id);
        $newsletter_helper->setTitle($newsletter['var_nom_newsletter']);
        $newsletter_helper->setMonth($this->getFrenchMonth());
        $news = $news->getActualitesBoxByIdNewsLetter($id);
        $columns = array();

        foreach ($news as $value) {
            if ($value['var_column'] == 'col01') {
                $columns[1][] = $value;
            } else {
                $columns[2][] = $value;
            }
        }

        $groupmonth = array();
        $ord = 1;
        foreach ($actualites as $row) {
            $groupmonth[$row['var_monthyear']] = $ord;
            $ord++;
        }

        $newsletter_helper->setMonthActualites($groupmonth);
        $date = $this->getDataFrance(FALSE);
        $smarty->assign(array(
            'BASE_URL' => JLTools::getInstance()->getNameDomain(),
            'DATE' => $date,
            'NEWSLETTER' => $newsletter,
            'NEWS1' => $columns[1],
            'NEWS2' => $columns[2],
            'BROWSER' => $for_browser,
            'HELPER' => $newsletter_helper
        ));

        $_SESSION[NEWSLETTER_KEY] = $smarty->fetch(JLPATH_WEB_SITE . DS . 'images' . DS . 'mail' . DS . 'newsletter.html');

        if ($this->Ajax->isAjaxRequest()) {
            echo json_encode('ok');
        } else {
            return $_SESSION[NEWSLETTER_KEY];
        }
    }

    function showNewsletter() {
        require JLPATH_MODELS . DS . 'AffiliesModel.php';

        $id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
        $code = filter_var($_GET['code'], FILTER_SANITIZE_STRING);
        $aff = new AffiliesModel();
        $aff = $aff->getAffilieByCode($code);
        $message = $this->getMessageNewsletter($id, TRUE);
        $message = str_replace("%FULLNAME%", $aff["var_fullname"], $message);
        $message = str_replace("%CODE%", $code, $message);
        echo $message;
    }

    function programSending() {
        $id = filter_var($_POST['_id'], FILTER_SANITIZE_NUMBER_INT);

        if (!empty($id) && $this->Ajax->isAjaxRequest()) {

            include_once JLPATH_MODELS . DS . 'AffiliesModel.php';
            $aff = new AffiliesModel();
            $aff->updateAffiliesSent(0);

            include_once JLPATH_MODELS . DS . 'NewsletterModel.php';
            $news = new NewsletterModel();
            $news->updateNewslettersSent(0);
            $news->updateNewsletterSent($id, 1);
            echo 'OK';
        }
    }

}